package com.zerox.springsecuritydemo329.filter;


import com.zerox.springsecuritydemo329.pojo.LoginUser;
import com.zerox.springsecuritydemo329.utils.JwtUtil;
import com.zerox.springsecuritydemo329.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 检查、验证token
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        // 不存在token
        if (!StringUtils.hasText(token)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }

        //存在token
        try {
            Claims claims = JwtUtil.parseJWT(token);
            String userId = claims.getSubject();

            // 改为从缓存里查用户， 什么时候把用户信息存到缓存里？
            LoginUser loginUser = redisCache.getCacheObject("login:"+userId);
            if (Objects.isNull(loginUser)){
                throw new RuntimeException("用户未登录");
            }

            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());

            // 告诉springsecurity 当前请求是哪个用户的
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            //放行
            filterChain.doFilter(request, response);

        } catch (Exception e) {
            throw new RuntimeException("token不合法");
        }

    }
}
